package com.jijuxie.message.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jijuxie.message.domain.ChatMessage;
import com.jijuxie.message.mapper.ChatMessageMapper;
import com.jijuxie.message.service.IChatMessageService;
import com.jijuxie.message.vo.ChatMessageVO;
import com.jijuxie.message.websocket.WebSocketServer;
import com.jijuxie.system.domain.SysUser;
import com.jijuxie.system.service.ISysUserService;

@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

    private static final Logger log = LoggerFactory.getLogger(ChatMessageServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public void sendMessage(ChatMessage message) {
        message.setReadFlag("0");
        message.setDelFlag("0");
        message.setSendTime(LocalDateTime.now());
        save(message);

        // 如果接收者在线，则实时推送消息
        webSocketServer.sendMessageToUser(message.getToUserId(), message);
    }

    @Override
    public Page<ChatMessage> getChatHistory(Long fromUserId, Long toUserId, Integer pageNum, Integer pageSize) {
        Page<ChatMessage> page = new Page<>(pageNum, pageSize);
        return page(page, new LambdaQueryWrapper<ChatMessage>()
                .nested(q -> q
                .eq(ChatMessage::getFromUserId, fromUserId)
                .eq(ChatMessage::getToUserId, toUserId)
                .or()
                .eq(ChatMessage::getFromUserId, toUserId)
                .eq(ChatMessage::getToUserId, fromUserId)
                )
                .eq(ChatMessage::getDelFlag, "0")
                .orderByAsc(ChatMessage::getSendTime));
    }

    @Override
    public void markRead(Long fromUserId, Long toUserId) {
        lambdaUpdate()
                .set(ChatMessage::getReadFlag, "1")
                .eq(ChatMessage::getFromUserId, fromUserId)
                .eq(ChatMessage::getToUserId, toUserId)
                .eq(ChatMessage::getReadFlag, "0")
                .update();
    }

    @Override
    public Long getUnreadCount(Long fromUserId, Long toUserId) {
        return lambdaQuery()
                .eq(ChatMessage::getFromUserId, fromUserId)
                .eq(ChatMessage::getToUserId, toUserId)
                .eq(ChatMessage::getReadFlag, "0")
                .count();
    }

    @Override
    public Page<ChatMessageVO> getMessageList(Long userId, Integer pageNum, Integer pageSize) {
        // 使用缓存键
        String cacheKey = "chat:list:" + userId + ":" + pageNum + ":" + pageSize;
        
        try {
            // 这里添加缓存逻辑，实际实现时应当注入缓存服务
            // 检查Redis中是否有缓存
            
            Page<ChatMessage> page = new Page<>(pageNum, pageSize);
            List<ChatMessage> lastMessages = this.baseMapper.selectLastMessages(userId);
            List<ChatMessageVO> voList = convertToVOList(lastMessages, userId);

            Page<ChatMessageVO> resultPage = new Page<>(pageNum, pageSize);
            resultPage.setRecords(voList);
            resultPage.setTotal(voList.size());
            
            // 将结果存入缓存，缓存30秒
            // 缓存服务.set(cacheKey, resultPage, 30);
            
            return resultPage;
        } catch (Exception e) {
            // 记录详细错误
            log.error("获取聊天列表失败: userId={}, pageNum={}, pageSize={}, error={}", 
                     userId, pageNum, pageSize, e.getMessage(), e);
                     
            // 返回空结果而不是抛出异常
            Page<ChatMessageVO> emptyPage = new Page<>(pageNum, pageSize);
            emptyPage.setRecords(new ArrayList<>());
            emptyPage.setTotal(0);
            return emptyPage;
        }
    }

    private List<ChatMessageVO> convertToVOList(List<ChatMessage> messages, Long userId) {
        return messages.stream().map(msg -> {
            ChatMessageVO vo = new ChatMessageVO();
            Long targetUserId = msg.getFromUserId().equals(userId)
                    ? msg.getToUserId() : msg.getFromUserId();
            SysUser targetUser = userService.getById(targetUserId);

            vo.setTargetUserId(targetUserId);
            vo.setTargetUserName(targetUser.getUsername());
            vo.setAvatar(targetUser.getAvatar());
            vo.setLastMessage(msg.getContent());
            vo.setLastTime(msg.getSendTime());
            vo.setUnreadCount(getUnreadCount(targetUserId, userId).intValue());

            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ChatMessage> getUnreadMessages(Long userId) {
        return lambdaQuery()
                .eq(ChatMessage::getToUserId, userId)
                .eq(ChatMessage::getReadFlag, "0")
                .eq(ChatMessage::getDelFlag, "0")
                .orderByDesc(ChatMessage::getSendTime)
                .last("LIMIT 100")
                .list();
    }
}